package com.housekeeperapp.persistence;

import android.content.Context;
import android.content.SharedPreferences;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;

/**
 * Created by xiaolong.wei on 2018/11/26.
 */

public class SharedPreferencesModule extends ReactContextBaseJavaModule {

    private Context mContext;
    private SharedPreferences sp;
    public SharedPreferencesModule(ReactApplicationContext reactContext) {
        super(reactContext);
        mContext = reactContext;
        sp = mContext.getSharedPreferences("HouseKeeper",Context.MODE_PRIVATE);
    }

    @Override
    public String getName() {
        return "SharedPreferences";
    }

    @ReactMethod
    public void saveInt(String key,final ReadableMap params){
        if (sp == null) {
            sp = mContext.getSharedPreferences("HouseKeeper", Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sp.edit();
        int value = params.getInt(key);
        edit.putInt(key,value).apply();

    }

    @ReactMethod
    public void saveString(String key , final ReadableMap params){
        if (sp == null){
            sp = mContext.getSharedPreferences("HouseKeeper", Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sp.edit();
        String value = params.getString(key);
        edit.putString(key,value).apply();
    }

    @ReactMethod
    public void saveBoolean(String key , final ReadableMap params){
        if (sp == null){
            sp = mContext.getSharedPreferences("HouseKeeper", Context.MODE_PRIVATE);
        }
        SharedPreferences.Editor edit = sp.edit();
        boolean value = params.getBoolean(key);
        edit.putBoolean(key,value).apply();
    }

    @ReactMethod
    public void getInt(String key,  Callback callback){
        if (sp == null){
            sp = mContext.getSharedPreferences("HouseKeeper", Context.MODE_PRIVATE);
        }
        int value = sp.getInt(key, -1);
        callback.invoke(value);
    }

    @ReactMethod
    public void getString(String key,  Callback callback){
        if (sp == null){
            sp = mContext.getSharedPreferences("HouseKeeper", Context.MODE_PRIVATE);
        }
        String value = sp.getString(key, null);
        callback.invoke(value);
    }

    @ReactMethod
    public void getBoolean(String key, Callback callback){
        if (sp == null){
            sp = mContext.getSharedPreferences("HouseKeeper", Context.MODE_PRIVATE);
        }
        boolean value = sp.getBoolean(key, false);
        callback.invoke(value);
    }
}
